use std::sync::Arc;
use parking_lot::Mutex;
use tauri::Window;
use std::time::Duration;

mod events;
mod processor;
mod state;
mod playback;

pub use playback::{PlaybackThread, PlaybackCommand};
pub use state::{PlayerState, PlaybackStatus};
pub use events::send_error;

use crate::config::PlayerConfig;
use crate::config::PlaybackHistory;

pub type Result<T> = std::result::Result<T, anyhow::Error>;

/// 播放管理器，负责管理播放状态和线程
pub struct PlaybackManager {
    pub player: PlayerConfig,
    pub history: Vec<PlaybackHistory>,
    state: Arc<Mutex<PlayerState>>,
    playback_thread: Arc<Mutex<Option<PlaybackThread>>>,
    window: Window,
    #[allow(dead_code)]
    config: PlayerConfig,
}

impl PlaybackManager {
    pub fn new(window: Window) -> Self {
        log::info!("Creating new PlaybackManager");
        Self {
            state: Arc::new(Mutex::new(PlayerState::new())),
            playback_thread: Arc::new(Mutex::new(None)),
            window: window.clone(),
            config: PlayerConfig::default(),
            player: PlayerConfig::default(),
            history: Vec::new(),
        }
    }

    pub fn with_config(window: Window, config: PlayerConfig) -> Self {
        log::info!("Creating new PlaybackManager with config");
        Self {
            state: Arc::new(Mutex::new(PlayerState::new())),
            playback_thread: Arc::new(Mutex::new(None)),
            window: window.clone(),
            config,
            player: PlayerConfig::default(),
            history: Vec::new(),
        }
    }

    pub fn load_media(&mut self, path: &str) -> Result<()> {
        log::info!("Loading media: {}", path);
        
        // 停止现有播放
        if let Some(thread) = &*self.playback_thread.lock() {
            thread.send_command(PlaybackCommand::Stop)?;
        }
        
        // 创建新的播放线程
        let playback_thread = PlaybackThread::new(
            path.to_string(),  // 转换为 String
            self.window.clone(),
            self.config.clone(),
        )?;
        
        // 更新状态
        self.state.lock().set_status(PlaybackStatus::Ready);
        
        // 存储播放线程
        *self.playback_thread.lock() = Some(playback_thread);
        
        Ok(())
    }

    pub fn play(&self) -> Result<()> {
        log::info!("Play command received");
        if let Some(thread) = &*self.playback_thread.lock() {
            thread.send_command(PlaybackCommand::Play)?;
        } else {
            send_error(&self.window, -1, "No media loaded", None)?;
        }
        Ok(())
    }

    pub fn pause(&self) -> Result<()> {
        log::info!("Pause command received");
        if let Some(thread) = &*self.playback_thread.lock() {
            thread.send_command(PlaybackCommand::Pause)?;
        }
        Ok(())
    }

    pub fn seek(&self, position: f64) -> Result<()> {
        log::info!("Seek command received: {} seconds", position);
        if let Some(thread) = &*self.playback_thread.lock() {
            let duration = Duration::from_secs_f64(position);
            thread.send_command(PlaybackCommand::Seek(duration))?;
        }
        Ok(())
    }

    pub fn set_volume(&self, volume: f32) -> Result<()> {
        log::info!("Set volume command received: {}", volume);
        if let Some(thread) = &*self.playback_thread.lock() {
            let volume = volume.max(0.0).min(1.0);
            thread.send_command(PlaybackCommand::SetVolume(volume))?;
        }
        Ok(())
    }

    pub fn set_muted(&self, muted: bool) -> Result<()> {
        log::info!("Set muted command received: {}", muted);
        if let Some(thread) = &*self.playback_thread.lock() {
            thread.send_command(PlaybackCommand::SetMuted(muted))?;
        }
        Ok(())
    }

    pub fn set_speed(&self, speed: f32) -> Result<()> {
        log::info!("Set speed command received: {}", speed);
        if let Some(thread) = &*self.playback_thread.lock() {
            let speed = speed.max(0.25).min(4.0);
            thread.send_command(PlaybackCommand::SetSpeed(speed))?;
        }
        Ok(())
    }

    pub fn update_config(&mut self, config: PlayerConfig) -> Result<()> {
        log::info!("Updating player config");
        self.config = config;
        
        // 如果有活动的播放线程，更新其配置
        if let Some(thread) = &*self.playback_thread.lock() {
            thread.send_command(PlaybackCommand::UpdateConfig(self.config.clone()))?;
        }
        
        Ok(())
    }

    pub fn cleanup(&self) -> Result<()> {
        log::info!("Cleaning up PlaybackManager");
        if let Some(thread) = &*self.playback_thread.lock() {
            thread.send_command(PlaybackCommand::Stop)?;
        }
        *self.playback_thread.lock() = None;
        Ok(())
    }

    pub fn get_state(&self) -> Result<PlayerState> {
        Ok(self.state.lock().clone())
    }

    pub fn save(&self) -> Result<()> {
        // 实现保存逻辑
        Ok(())
    }

    pub fn add_to_history(&mut self, _path: String, _position: f64) {
        // 实现留空或添加 #[allow(dead_code)]
    }

    pub fn get_last_position(&self, _path: &str) -> Option<f64> {
        // 实现示例
        None
    }
}

impl Drop for PlaybackManager {
    fn drop(&mut self) {
        if let Err(e) = self.cleanup() {
            log::error!("Error during PlaybackManager cleanup: {}", e);
        }
    }
}
